﻿using System;
using System.Collections.Generic;
using System.Text;
using Wjtour.Common;
using System.Linq;
using System.Data.Common;
using System.Data;

namespace Wjtour.BLL
{
    public class link_bll : base_dll
    {
        public PaginationData<Wjtour.Domain.link> GetList(string q, int page, int pagesize = 20)
        {
            string where = " where 1=1";
            if (!string.IsNullOrEmpty(q))
                where += " and (title like '%" + Utility.GetSafeSql(q) + "%' or url like '%" + Utility.GetSafeSql(q) + "%') ";
            string sql = string.Format(@"select * from link 
                {0} 
                order by id desc", where);
            PaginationData<Wjtour.Domain.link> data = GetPaginationData<Wjtour.Domain.link>(sql, page, pagesize);
            return data;
        }

        public Wjtour.Domain.link Load(int id)
        {
            string sql = "select * from link where id=" + id;
            return DbAccess.GetObjects<Wjtour.Domain.link>(sql).FirstOrDefault();
        }

        public bool Save(Wjtour.Domain.link entity)
        {
            string sql = "";

            DbCommand cmd = DbAccess.CreateCommand();

            if (entity.id > 0)
            {
                sql = @"UPDATE [link] SET 
                [url] = @url,
                [title] = @title,
                [addtime] = @addtime,
                [type] = @type,
                [img] = @img,
                [sort] = @sort
                 WHERE id=@id";
                DbAccess.AddInParameter(cmd, "@id", DbType.Int32, entity.id);

            }
            else
            {
                sql = @"INSERT INTO [link]( 
                [url],[title],[addtime],[type],[img],[sort])VALUES(
                @url,@title,@addtime,@type,@img,@sort)";
            }
            DbAccess.AddInParameter(cmd, "@url", DbType.String, entity.url);
            DbAccess.AddInParameter(cmd, "@title", DbType.String, entity.title);
            DbAccess.AddInParameter(cmd, "@addtime", DbType.DateTime, entity.addtime);
            DbAccess.AddInParameter(cmd, "@type", DbType.Int32, entity.type);
            DbAccess.AddInParameter(cmd, "@img", DbType.String, entity.img);
            DbAccess.AddInParameter(cmd, "@sort", DbType.Int32, entity.sort);
            cmd.CommandText = sql;
            cmd.CommandType = System.Data.CommandType.Text;
            return DbAccess.ExecuteNonQuery(cmd) > 0;

        }
        public int BatchDelete(string ids)
        {
            string sql = "delete from link where id in(" + ids + ")";
            return DbAccess.ExecuteNonQuery(sql);
        }
    }
}
